<template>
  <div class="pinyin-quick-nav">
    <!-- 快速导航对话框 -->
    <el-dialog
      v-model="visible"
      :show-close="false"
      :modal="true"
      width="650px"
      top="15vh"
      class="quick-nav-dialog"
    >
      <div class="quick-nav-content">
        <!-- 搜索输入框 -->
        <div class="search-box">
          <el-icon class="search-icon"><Search /></el-icon>
          <input
            ref="searchInputRef"
            v-model="searchText"
            type="text"
            class="search-input"
            placeholder="输入拼音首字母或关键词快速导航... (如: htgl = 合同管理)"
            @input="handleSearch"
            @keydown="handleKeydown"
          />
          <el-tag v-if="searchText" size="small" class="search-tip">
            {{ resultCount }} 个结果
          </el-tag>
        </div>

        <!-- 快捷提示 -->
        <div v-if="!searchText" class="search-tips">
          <div class="tip-title">
            <el-icon><Lightbulb /></el-icon>
            试试这些快捷搜索：
          </div>
          <div class="tip-list">
            <el-tag 
              v-for="tip in quickTips" 
              :key="tip.key"
              size="small"
              effect="plain"
              class="tip-tag"
              @click="searchText = tip.key"
            >
              {{ tip.key }} - {{ tip.title }}
            </el-tag>
          </div>
        </div>

        <!-- 搜索结果 -->
        <div v-else class="search-results">
          <div 
            v-for="(item, index) in filteredResults" 
            :key="item.path"
            class="result-item"
            :class="{ 'is-selected': index === selectedIndex }"
            @click="navigateTo(item)"
            @mouseenter="selectedIndex = index"
          >
            <div class="result-icon" :style="{ background: item.gradient || '#409eff' }">
              <el-icon><component :is="item.icon" /></el-icon>
            </div>
            <div class="result-content">
              <div class="result-title">
                <span v-html="highlightMatch(item.title)"></span>
                <el-tag v-if="item.badge" :type="item.badgeType || 'primary'" size="small">
                  {{ item.badge }}
                </el-tag>
              </div>
              <div class="result-path">{{ item.path }}</div>
              <div v-if="item.description" class="result-desc">{{ item.description }}</div>
            </div>
            <div class="result-meta">
              <el-tag v-if="item.category" size="small" effect="plain">
                {{ item.category }}
              </el-tag>
              <div class="result-shortcut">
                <kbd v-if="index < 9">{{ index + 1 }}</kbd>
                <span v-else>Enter</span>
              </div>
            </div>
          </div>

          <el-empty v-if="filteredResults.length === 0" description="未找到匹配的功能" :image-size="80">
            <el-button type="primary" size="small" @click="searchText = ''">
              清空搜索
            </el-button>
          </el-empty>
        </div>

        <!-- 底部快捷键提示 -->
        <div class="search-footer">
          <div class="footer-tips">
            <span><kbd>↑</kbd> <kbd>↓</kbd> 选择</span>
            <span><kbd>Enter</kbd> 打开</span>
            <span><kbd>Esc</kbd> 关闭</span>
            <span><kbd>1-9</kbd> 快速跳转</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import {
  Search, Lightbulb
} from '@element-plus/icons-vue'

const router = useRouter()

const visible = ref(false)
const searchText = ref('')
const searchInputRef = ref(null)
const selectedIndex = ref(0)

// 快捷提示
const quickTips = [
  { key: 'dkdpinyin', title: '低代码平台' },
  { key: 'htgl', title: '合同管理' },
  { key: 'zcgl', title: '资产管理' },
  { key: 'sbgl', title: '设备管理' },
  { key: 'xsdd', title: '销售订单' },
  { key: 'cgdd', title: '采购订单' }
]

// 所有可导航的功能（包含拼音）
const allNavigations = ref([
  // 低代码平台
  { 
    path: '/lowcode', 
    title: '低代码平台', 
    pinyin: 'dkdpinyin', 
    icon: 'MagicStick',
    category: '低代码',
    badge: 'HOT',
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    description: 'AI驱动的可视化开发平台'
  },
  { path: '/lowcode/form-designer', title: '表单设计器', pinyin: 'bdsj', icon: 'Edit', category: '低代码' },
  { path: '/lowcode/page-designer', title: '页面设计器', pinyin: 'ymsjq', icon: 'Document', category: '低代码' },
  { path: '/lowcode/ai-assistant', title: 'AI助手', pinyin: 'aizs', icon: 'MagicStick', category: '低代码', badge: 'AI' },
  
  // 合同管理
  { 
    path: '/contract/list', 
    title: '合同管理', 
    pinyin: 'htgl', 
    icon: 'Document',
    category: '合同',
    badge: 'NEW',
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    description: '合同全生命周期管理'
  },
  { path: '/contract/create', title: '新建合同', pinyin: 'xjht', icon: 'DocumentAdd', category: '合同' },
  { path: '/contract/approval', title: '合同审批', pinyin: 'htsp', icon: 'CircleCheck', category: '合同' },
  
  // 资产管理
  { 
    path: '/asset/list', 
    title: '资产管理', 
    pinyin: 'zcgl', 
    icon: 'Box',
    category: '资产',
    badge: 'NEW',
    gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    description: '资产全生命周期管理'
  },
  
  // 设备管理
  { 
    path: '/equipment/ledger', 
    title: '设备管理', 
    pinyin: 'sbgl', 
    icon: 'SetUp',
    category: '设备',
    badge: 'NEW',
    gradient: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    description: '生产设备专业化管理'
  },
  { path: '/equipment/oee', title: '设备效率OEE', pinyin: 'sbxl', icon: 'TrendCharts', category: '设备', badge: 'HOT' },
  
  // 销售管理
  { path: '/sales/orders', title: '销售订单', pinyin: 'xsdd', icon: 'ShoppingCart', category: '销售' },
  { path: '/sales/quotation', title: '销售报价', pinyin: 'xsbj', icon: 'Money', category: '销售' },
  
  // 采购管理
  { path: '/purchase/orders', title: '采购订单', pinyin: 'cgdd', icon: 'Document', category: '采购' },
  { path: '/purchase/suppliers', title: '供应商管理', pinyin: 'gysgl', icon: 'OfficeBuilding', category: '采购' },
  
  // 库存管理
  { path: '/inventory/products', title: '商品管理', pinyin: 'spgl', icon: 'Goods', category: '库存' },
  { path: '/inventory/stock', title: '库存查询', pinyin: 'kccx', icon: 'Box', category: '库存' },
  
  // 财务管理
  { path: '/finance/voucher', title: '凭证管理', pinyin: 'pzgl', icon: 'DocumentCopy', category: '财务' },
  { path: '/finance/accounts', title: '科目管理', pinyin: 'kmgl', icon: 'Files', category: '财务' },
  
  // 系统管理
  { path: '/system/users', title: '用户管理', pinyin: 'yhgl', icon: 'User', category: '系统' },
  { path: '/system/roles', title: '角色管理', pinyin: 'jsgl', icon: 'UserFilled', category: '系统' },
  { path: '/system/menu', title: '菜单管理', pinyin: 'cdgl', icon: 'Menu', category: '系统' }
])

// 搜索结果
const filteredResults = computed(() => {
  if (!searchText.value) return []
  
  const keyword = searchText.value.toLowerCase()
  
  return allNavigations.value.filter(item => {
    // 匹配拼音首字母
    if (item.pinyin && item.pinyin.includes(keyword)) {
      return true
    }
    // 匹配标题
    if (item.title.includes(searchText.value)) {
      return true
    }
    // 匹配路径
    if (item.path.toLowerCase().includes(keyword)) {
      return true
    }
    // 匹配描述
    if (item.description && item.description.includes(searchText.value)) {
      return true
    }
    return false
  }).slice(0, 10) // 最多显示10个结果
})

const resultCount = computed(() => filteredResults.value.length)

// 高亮匹配文本
const highlightMatch = (text) => {
  if (!searchText.value) return text
  const keyword = searchText.value
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, '<span class="highlight">$1</span>')
}

// 搜索处理
const handleSearch = () => {
  selectedIndex.value = 0
}

// 键盘事件
const handleKeydown = (event) => {
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      selectedIndex.value = Math.min(selectedIndex.value + 1, filteredResults.value.length - 1)
      break
    case 'ArrowUp':
      event.preventDefault()
      selectedIndex.value = Math.max(selectedIndex.value - 1, 0)
      break
    case 'Enter':
      event.preventDefault()
      if (filteredResults.value[selectedIndex.value]) {
        navigateTo(filteredResults.value[selectedIndex.value])
      }
      break
    case 'Escape':
      event.preventDefault()
      visible.value = false
      break
    default:
      // 数字键1-9快速跳转
      if (event.key >= '1' && event.key <= '9') {
        const index = parseInt(event.key) - 1
        if (filteredResults.value[index]) {
          event.preventDefault()
          navigateTo(filteredResults.value[index])
        }
      }
  }
}

// 导航
const navigateTo = (item) => {
  router.push(item.path)
  visible.value = false
  searchText.value = ''
}

// 全局快捷键
const handleGlobalKeydown = (event) => {
  // Ctrl + K 或 Cmd + K 打开快速导航
  if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
    event.preventDefault()
    visible.value = true
    nextTick(() => {
      searchInputRef.value?.focus()
    })
  }
  
  // Ctrl + P 或 Cmd + P 也可以打开
  if ((event.ctrlKey || event.metaKey) && event.key === 'p') {
    event.preventDefault()
    visible.value = true
    nextTick(() => {
      searchInputRef.value?.focus()
    })
  }
}

// 监听visible变化
watch(visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      searchInputRef.value?.focus()
    })
  } else {
    searchText.value = ''
    selectedIndex.value = 0
  }
})

onMounted(() => {
  document.addEventListener('keydown', handleGlobalKeydown)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleGlobalKeydown)
})

// 暴露方法
defineExpose({
  open: () => { visible.value = true }
})
</script>

<style scoped>
:deep(.quick-nav-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.quick-nav-dialog .el-dialog__header) {
  display: none;
}

:deep(.quick-nav-dialog .el-dialog__body) {
  padding: 0;
}

.quick-nav-content {
  display: flex;
  flex-direction: column;
  max-height: 70vh;
}

/* 搜索框 */
.search-box {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
}

.search-icon {
  font-size: 20px;
  color: #909399;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  color: #303133;
  background: transparent;
}

.search-input::placeholder {
  color: #c0c4cc;
}

.search-tip {
  flex-shrink: 0;
}

/* 快捷提示 */
.search-tips {
  padding: 20px 24px;
}

.tip-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.tip-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tip-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.tip-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

/* 搜索结果 */
.search-results {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 4px;
}

.result-item:hover,
.result-item.is-selected {
  background: #ecf5ff;
}

.result-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  flex-shrink: 0;
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 4px;
}

.result-title :deep(.highlight) {
  color: #409eff;
  background: #ecf5ff;
  padding: 0 4px;
  border-radius: 3px;
}

.result-path {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.result-desc {
  font-size: 12px;
  color: #c0c4cc;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.result-shortcut kbd,
.result-shortcut span {
  display: inline-block;
  padding: 2px 6px;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  font-size: 12px;
  color: #606266;
  font-family: monospace;
}

/* 底部提示 */
.search-footer {
  padding: 12px 24px;
  border-top: 1px solid #e4e7ed;
  background: #f5f7fa;
}

.footer-tips {
  display: flex;
  gap: 20px;
  font-size: 12px;
  color: #909399;
}

.footer-tips kbd {
  display: inline-block;
  padding: 2px 6px;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  font-size: 11px;
  color: #606266;
  font-family: monospace;
  margin: 0 2px;
}

/* 滚动条 */
.search-results::-webkit-scrollbar {
  width: 6px;
}

.search-results::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.search-results::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>

